<template>
  <div class="box">
    <!--  状态流程图  -->
    <div class="header-box">
      <!--   rowsIndex%2 == 1 偶数行   rowsIndex%2 == 0 奇数行   -->
      <a-row
          :wrap="true"
          v-for="(rows, rowsIndex) in flowRows"
          :key="rowsIndex"
          type="flex"
          :gutter="[0, 50]"
          :justify="rowsIndex % 2 == 0 ? '' : 'end'"
          :style="{
          marginBottom: rowsIndex + 1 !== flowRows.length ? '50px' : 0,
        }"
          :class="rowsIndex % 2 == 1 ? 'row-even' : 'row-odd'"
      >
        <template v-for="(item, index) in rows" :key="index">
          <a-col :span="3" v-if="!item.isBranch">
            <div class="item-box">
              <div class="item-content">
                <a-tooltip
                    placement="top"
                    :title="item.name"
                    :visible="item.isOpen"
                >
                  <div
                      class="content-name"
                      @mouseenter="
                      (e) => {
                        handleEnter(e, item);
                      }
                    "
                      @mouseleave="item.isOpen = false"
                  >
                    {{ item.name }}
                  </div>
                </a-tooltip>

                <div class="next-row" v-if="item.lineFeed">
                  <CaretDownOutlined
                      style="color: #2681f3"
                      class="next-row-icon"
                  />
                </div>
              </div>
              <div
                  class="arrow arrow-odd"
                  v-if="
                  (rowsIndex % 2 == 0 && index + 1 !== rows.length) ||
                  (rowsIndex % 2 == 1 && index + 1 !== rows.length)
                "
              >
                <CaretRightOutlined
                    v-if="rowsIndex % 2 == 0"
                    class="right-arrow"
                    style="color: #2681f3"
                />
                <CaretLeftOutlined
                    v-if="rowsIndex % 2 == 1"
                    class="left-arrow"
                    style="color: #2681f3"
                />
              </div>
            </div>
          </a-col>
          <template v-if="item.children?.length">
            <a-col :span="3">
              <a-row
                  :wrap="true"
                  :gutter="[0, 16]"
                  class="children-row"
                  :class="
                  rowsIndex % 2 == 0
                    ? 'children-row-odd'
                    : rows.length == 1 && rowsIndex % 2 == 1
                    ? 'children-row-even'
                    : 'children-row-even children-row-even-link'
                "
              >
                <a-col
                    :span="24"
                    v-for="(child, childIndex) in item.children"
                    :key="childIndex"
                >
                  <div class="item-box">
                    <div
                        v-if="rowsIndex % 2 == 0"
                        :class="
                        childIndex == 0
                          ? 'first-row'
                          : childIndex + 1 == item.children.length
                          ? 'last-row'
                          : 'arrow'
                      "
                    >
                      <CaretRightOutlined
                          v-if="rowsIndex % 2 == 0"
                          class="right-arrow"
                          style="color: #2681f3"
                      />
                      <CaretLeftOutlined
                          v-if="rowsIndex % 2 == 1"
                          class="left-arrow"
                          style="color: #2681f3"
                      />
                    </div>
                    <div class="item-content">
                      <a-tooltip
                          placement="top"
                          :title="child.name"
                          :visible="child.isOpen"
                      >
                        <div
                            class="content-name"
                            @mouseenter="
                            (e) => {
                              handleEnter(e, child);
                            }
                          "
                            @mouseleave="child.isOpen = false"
                        >
                          {{ child.name }}
                        </div>
                      </a-tooltip>
                    </div>
                    <div
                        v-if="rowsIndex % 2 == 1"
                        :class="
                        childIndex == 0
                          ? 'first-row'
                          : childIndex + 1 == item.children.length
                          ? 'last-row'
                          : 'arrow'
                      "
                    >
                      <CaretRightOutlined
                          v-if="rowsIndex % 2 == 0"
                          class="right-arrow"
                          style="color: #2681f3"
                      />
                      <CaretLeftOutlined
                          v-if="rowsIndex % 2 == 1"
                          class="left-arrow"
                          style="color: #2681f3"
                      />
                    </div>
                  </div>
                </a-col>
              </a-row>
            </a-col>
            <a-col
                :span="1"
                v-if="rows.length == 1 && rowsIndex % 2 == 1"
            ></a-col>
          </template>
        </template>
      </a-row>
    </div>

    <CustomTable
        ref="customTableRef"
        :columns="columns"
        :hasPagination="false"
        :requestInfo="{
          service: '/org', // 请求服务
          serviceUrl: '/business/customer/statusList', // 请求url
          serviceType: 'get', // 请求方式
        }"
        :extraParams="{}"
        :tableConfig="$store.getters.tableConfig"
        tableId="IntendedCustomerStatus"
        @request="$utils.commonRequest"
        @getListResult="getListResult"
        :rightButtons="rightButtons"
        :excludeImport="true"
        :excludeExport="true"
      >
      <template #column-action="{ record }">
          <a-button
              type="link"
              :disabled="record.is_root == 1"
              @click.stop="handleEdit(record)"
          >
            编辑
          </a-button>
          <a-button
              type="link"
              danger
              :disabled="record.is_root == 1"
              @click.stop="handleDelete(record)"
          >删除
          </a-button
          >
        </template>
    </CustomTable>

    <AddCustomerStatus
        :visible="addVisible"
        :id="editId"
        :editInfo="editInfo"
        @handleCancel="handleCancel"
        @success="handleSuccess"
    />
  </div>
</template>

<script>
import {
  reactive,
  ref,
  toRefs,
  computed,
  watch,
  defineComponent,
  createVNode,
} from "vue";
import request from "@/common/utils/request";
import {
  CaretRightOutlined,
  CaretLeftOutlined,
  CaretDownOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import _ from "lodash";
import AddCustomerStatus from "@/views/village/BusinessManage/modules/AddCustomerStatus.vue";
import {message, Modal} from "ant-design-vue";
import { CustomTable } from "bl-common-vue3";

export default defineComponent({
  name: "IntendedCustomerStatus",
  props: {
    activeKey: {
      type: [Number, String],
      default: "",
    },
  },
  components: {
    CaretRightOutlined,
    CaretLeftOutlined,
    CaretDownOutlined,
    AddCustomerStatus,
    CustomTable
  },
  setup(props, {emit}) {
        // tab表格实例
        const customTableRef = ref(null);

    const state = reactive({
      dataList: [],
      flowRows: [],
      columns: COLUMNS,
      loading: false,
      addVisible: false,
      editId: 0,
      editInfo: {},

      rightButtons:[
      {
          name: "+新增状态",
          key: "handleAdd",
          onClick: () => {
            handleAdd();
          },
          props: {
            type: "primary",
          },
        },
      ]
    });

    const getListResult=(resultData)=>{
        let flowData = _.cloneDeep(resultData?.list || []);
        let endData = flowData.filter((v) => v.is_end == 1);
        flowData = flowData.filter((v) => v.is_end == 0);
        flowData.push({isBranch: true, children: endData});
        let totalRow =
            flowData.length % 8 > 0
                ? parseInt(flowData.length / 8) + 1
                : parseInt(flowData.length / 8);
        flowData.forEach((item, index) => {
          let sort = index + 1;
          item.row =
              sort % 8 > 0 ? parseInt(sort / 8) + 1 : parseInt(sort / 8);
          item.lineFeed = sort % 8 == 0 && totalRow > item.row;
        });
        let rows = [];
        for (let i = 0; i < flowData.length; i += 8) {
          rows.push(flowData.slice(i, i + 8));
        }
        // 对偶数行的元素进行倒序排列
        for (let i = 1; i < rows.length; i += 2) {
          rows[i].reverse();
        }
        state.flowRows = rows;
    }

    const getDataList = () => {
          if(customTableRef.value){
            customTableRef.value.loadData(true);
          }
    };

    const handleAdd = () => {
      state.addVisible = true;
    };

    const handleEdit = (record) => {
      state.addVisible = true;
      state.editId = record.id;
      state.editInfo = _.cloneDeep(record);
    };

    const handleCancel = () => {
      state.addVisible = false;
      state.editId = 0;
      state.editInfo = {};
    };

    const handleSuccess = () => {
      handleCancel();
      init();
    };

    const handleDelete = (record) => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要删除该状态吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          request
              .del("/org", "/business/customer/statusDel", {id: record.id})
              .then((res) => {
                message.success(res?.msg || "删除成功");
                init();
              });
        },
      });
    };

    const changeInitialCheck = (e, item) => {
      let is_initial = e.target.checked ? 1 : 0;
      request
          .put("/org", "/business/customer/statusEdit", {
            id: item.id,
            is_initial,
          })
          .then((res) => {
            message.success(res?.msg || "操作成功!");
            init();
          });
    };

    const changeCheck = (e, item) => {
      let is_end = e.target.checked ? 1 : 0;
      request
          .put("/org", "/business/customer/statusEdit", {id: item.id, is_end})
          .then((res) => {
            message.success(res?.msg || "操作成功!");
            init();
          });
    };

    const init = () => {
      getDataList();
    };

    watch(
        () => props.activeKey,
        (val) => {
          if (val) {
            if (val == 6) {
              init();
            }
          }
        },
        {immediate: true})

    const isBeyond = (e) => {
      const ev = window.event || e;
      const textContent = ev.target;
      const clientW = textContent.clientWidth;
      const scrollW = textContent.scrollWidth;
      return scrollW > clientW; // true为溢出  false为不溢出
    };
    const handleEnter = (e, item) => {
      item.isOpen = isBeyond(e);
    };
    return {
      ...toRefs(state),
      handleEnter,
      handleSuccess,
      handleCancel,
      handleAdd,
      handleEdit,
      handleDelete,
      changeCheck,
      changeInitialCheck,
      getListResult,
      customTableRef
    };
  },
});

const COLUMNS = [
  {
    title: "排序",
    align: "center",
    dataIndex: "sort",
    key: "sort",
  },
  {
    title: "跟进状态",
    align: "center",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "阶段描述",
    align: "center",
    dataIndex: "desc",
    key: "desc",
    width: "20%",
    customRender: ({text}) => {
      return text || "--";
    },
  },
  {
    title: "初始状态",
    align: "center",
    dataIndex: "is_initial",
    key: "is_initial",
  },
  {
    title: "结束状态",
    align: "center",
    dataIndex: "is_end",
    key: "is_end",
  },
  {
    title: "操作",
    align: "center",
    dataIndex: "action",
    key: "action",
    width: 180,
    fixed: "right",
  },
];
</script>

<style lang="less" scoped>
.box {
  padding: 10px;

  .header-clue {
    padding: 0 14px;
  }

  .header-box {
    background: #fff;
    padding: 14px 10px;
  }

  .header {
    background-color: rgb(240, 242, 245);
    padding: 16px 10px;

    .num-info {
      color: @primary-color;
      font-size: 30px;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }
  }

  .header-content {
    width: 0;
  }
}

:deep(.ant-tabs-content) {
  height: 100%;
}

.item-box {
  width: 100%;
  display: flex;

  .item-content {
    width: 60%;
    height: 40px;
    border: 1px solid @primary-color;
    border-radius: 4px;
    position: relative;
    color: @primary-color;

    .content-name {
      width: 100%;
      height: 100%;
      line-height: 40px;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }

    .next-row {
      width: 2px;
      height: 35px;
      background-color: @primary-color;
      position: absolute;
      top: 42px;
      left: 50%;

      .next-row-icon {
        position: absolute;
        bottom: -10px;
        left: -6px;
      }
    }
  }

  .arrow {
    flex: 1;
    height: 2px;
    background-color: @primary-color;
    margin: 19px 10px;
    position: relative;
  }

  .first-row {
    flex: 1;
    height: 2px;
    background-color: @primary-color;
    margin: 10px 10px 30px 10px;
    position: relative;
  }

  .last-row {
    flex: 1;
    height: 2px;
    background-color: @primary-color;
    margin: 30px 10px 10px 10px;
    position: relative;
  }

  .right-arrow {
    position: absolute;
    top: -6px;
    right: -10px;
  }

  .left-arrow {
    position: absolute;
    top: -6px;
    left: -10px;
  }
}

.children-row {
  position: relative;
}

.children-row-odd {
  .first-row {
    margin-left: 0;
  }

  .last-row {
    margin-left: 0;
  }

  .arrow {
    margin-left: 0;
  }

  &::before {
    content: "";
    position: absolute;
    height: calc(100% - 20px);
    width: 2px;
    background-color: @primary-color;
    left: 0px;
    top: 10px;
  }
}

.children-row-even {
  &::before {
    content: "";
    position: absolute;
    height: calc(100% - 20px);
    width: 2px;
    background-color: @primary-color;
    right: 10px;
    top: 10px;
  }
}

.children-row-even-link {
  &::after {
    content: "";
    position: absolute;
    height: 2px;
    width: 10px;
    background-color: @primary-color;
    right: 0px;
    top: 20px;
  }
}
</style>
